<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-02-23
 * Time: 16:59:52
 * Info: 后台基本设置
 */

namespace app\common\model;

use app\common\service\admin\CacheClearService;

class Config extends TimeInit
{

    /**
     * 定义后台配置分组常量
     */
    const GROUP_LIST = [
        'base'   => '基础配置',
        'mail'   => '邮件配置',
        'upload' => '附件配置',
        'safe'   => '高级配置',
        'user'   => '会员中心',
        'other'  => '其他'
    ];

    /**
     * 获取配置数据
     */
    public static function getConfigList()
    {
        $list = self::order(['weigh' => 'asc', 'id' => 'asc'])->select()->toArray();

        return $list;
    }

    //保存配置
    public static function saveData($param)
    {
        $msg = "保存成功";
        $url = "";

        $clearCacheAll = false;
        foreach ($param as $key => $value) {
            $arr[$key]       = $value;
            $value           = htmlspecialchars($value);
            $oldAdminUrlPass = get_config('admin_url_password');

            if ($key == 'admin_url_password') {
                //判断是否有后缀【.php】，如果没有需要加上
                if (strpos($value, '.php') === false) {
                    $value = $value.'.php';
                }
                //判断是否更改了后台加密码
                if ($oldAdminUrlPass != $value) {
                    $msg = "您修改了后台加密码，请退出重新登录!";
                    rename(ROOT_PATH.'/public/'.$oldAdminUrlPass, ROOT_PATH.'/public/'.$value);
                    $url           = cmf_get_domain()."/".$value."/login/index";
                    $clearCacheAll = true;
                }
            }

            self::strict(false)->where(['name' => $key])->data(['value' => $value])->update();
        }
        //清除缓存
        CacheClearService::clearSystemConfig($clearCacheAll);

        return ['msg' => $msg, 'url' => $url];
    }

    public static function customAdd($param)
    {
        $cha = self::where(['name' => $param['name']])->find();
        if ( ! empty($cha)) {
            return ['code' => 0, 'msg' => '配置名称已存在，请修改'];
        }
        if ($param['fieldtype'] == "radio" || $param['fieldtype'] == "select") {
            $data1   = explode('|', rtrim($param['setting'][$param['fieldtype']], '|'));
            $setting = json_encode($data1, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            $setting = str_replace("：", ":", $setting);
        } else {
            $setting = "";
        }
        $data = [
            'name'      => $param['name'],
            'fieldtype' => $param['fieldtype'],
            'group'     => 99,
            'title'     => $param['title'],
            'status'    => 1,
            'value'     => $param['value'][$param['fieldtype']],
            'setting'   => $setting
        ];
        try {
            self::create($data);
            //清除缓存
            CacheClearService::clearSystemConfig();
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => '操作失败<br>'.$e->getMessage()];
        }

        return ['code' => 200, 'msg' => '保存成功'];
    }

    public static function customEdit($param)
    {
        if (empty($param['id'])) {
            return ['code' => 0, 'msg' => '参数错误'];
        }
        $cha = self::where(['name' => $param['name']])->where('id', '<>', $param['id'])->find();
        if ( ! empty($cha)) {
            return ['code' => 0, 'msg' => '配置名称已存在，请修改'];
        }
        if ($param['fieldtype'] == "radio" || $param['fieldtype'] == "select") {
            $data1   = explode('|', rtrim($param['setting'][$param['fieldtype']], '|'));
            $setting = json_encode($data1, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            $setting = str_replace("：", ":", $setting);
        } else {
            $setting = "";
        }
        $data = [
            'fieldtype' => $param['fieldtype'],
            'group'     => 99,
            'title'     => $param['title'],
            'status'    => 1,
            'value'     => $param['value'][$param['fieldtype']],
            'setting'   => $setting
        ];
        try {
            self::update($data, ['id' => $param['id']]);
            //清除缓存
            CacheClearService::clearSystemConfig();
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => '操作失败<br>'.$e->getMessage()];
        }

        return ['code' => 200, 'msg' => '保存成功'];
    }

    public static function customDel($id)
    {
        self::destroy($id);
        //清除缓存
        CacheClearService::clearSystemConfig();
    }

}
